package com.anysoft.visitdd.example;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.logging.Logger;

/*rsa加密器*/
public class RsaEncrypter {
    private Cipher mCipher;
    private RSAPublicKey mPublicKey;

    public RsaEncrypter(String algorithm, String publicKey) {
        byte[] key_ba;
        try {
            mCipher = Cipher.getInstance(algorithm);
            var keyFactory = KeyFactory.getInstance(ProjectSecurityCommon.ALG_RSA);
            key_ba = Base64.getDecoder().decode(publicKey);
            mPublicKey = (RSAPublicKey) keyFactory.generatePublic(
                    new X509EncodedKeySpec(key_ba)
            );
            mCipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
        } catch (Exception e) {
            Logger.getGlobal().severe(e.getMessage());
        }
    }

    public String encrypt(String msg) throws Exception {
        String msg_e = null;
        var msg_ba = msg.getBytes();
        var msg_e_ba = ProjectSecurityCommon.rsaEncrypt(mCipher, msg_ba);
        msg_e = Base64.getEncoder().encodeToString(msg_e_ba);
        return msg_e;
    }
}
